import requests
from hashlib import md5
import time
import random
import re

url = "https://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule"

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36 Edg/92.0.902.62",
    "Referer": "https://fanyi.youdao.com/",
    "Cookie": "OUTFOX_SEARCH_USER_ID=512688694@10.169.0.102; JSESSIONID=aaaxkb_sIz1dThPLLogSx; OUTFOX_SEARCH_USER_ID_NCOO=68588117.42891903; fanyi-ad-id=113723; fanyi-ad-closed=1; ___rl__test__cookies=1627897214144"

}
while(1):
    word = input("请输入英文单词：")
    mach = re.match("^[A-Za-z]+$", word)
    if mach:
        break
    else:
        print("不要输入其他东西哦！")

lts = str(time.time() * 1000).split(".")[0]
salt = lts + str(random.randint(0, 10))
sign = md5(("fanyideskweb" + word + salt + "Y2FYu%TNSbMCxc3t2u^XT").encode("utf-8")).hexdigest()
bv = md5(headers["User-Agent"].encode("utf-8")).hexdigest()

data = {
    "i": word,
    "from": "AUTO",
    "to": "AUTO",
    "smartresult": "dict",
    "client": "fanyideskweb",
    "salt": salt,
    "sign": sign,
    "lts": lts,
    "bv": bv,
    "doctype": "json",
    "version": "2.1",
    "keyfrom": "fanyi.web",
    "action": "FY_BY_CLICKBUTTION"
}

resp = requests.post(url, headers=headers, data=data).json()
if resp['errorCode'] == 0:
    result = resp["translateResult"][0][0]['tgt']
    detail_result = resp['smartResult']['entries']

    print("--------------------------------------------")
    print("翻译结果：")
    print(result)
    print("-------------------------")
    print(word)
    for i in detail_result:
        print(i)
    print("--------------------------------------------")
elif resp['errorCode'] == 40:
    print("没有查询到这个单词！")
else:
    print("有道翻译接口解析失败，请重新分析！")